using FubuMVC.Core.Behaviors;
using NHibernate;

namespace complex.Behaviors
{
    public class TransactionBehavior
        : IActionBehavior
    {
        private readonly ISession session;

        public IActionBehavior InsideBehavior { get; set; }
        
        public TransactionBehavior(ISession session)
        {
            this.session = session;
        }

        public void Invoke()
        {
            using(var transaction = session.BeginTransaction())
            {
                try
                {
                    InsideBehavior.Invoke();
                    transaction.Commit();
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }

        public void InvokePartial()
        {
            InsideBehavior.InvokePartial();
        }
    }
}